import { RequestHandler } from 'express'
import { ClusterService, Metric } from '../helper/cluster.service'
import Config from '../config'
import * as prom from 'prom-client'

const register = new prom.Registry()

const DATABASE_CPU = new prom.Gauge({
  name: 'laf_mongo_cpu',
  help: 'the cpu of the mongo',
  registers: [register],
  labelNames: ['container', 'pod', 'appid'],
})

const DATABASE_MEMORY = new prom.Gauge({
  name: 'laf_mongo_memory',
  help: 'the memory of the mongo',
  registers: [register],
  labelNames: ['container', 'pod', 'appid'],
})

function updateMetrics(metric: Metric) {
  DATABASE_CPU.labels(metric.containerName, metric.podName, metric.appid).set(
    metric.cpu,
  )
  DATABASE_MEMORY.labels(
    metric.containerName,
    metric.podName,
    metric.appid,
  ).set(metric.memory)
}

const getDatabaseMetrics: RequestHandler = async (req, res) => {
  const token = req.params.token

  if (!token || Config.API_SECRET !== token) {
    return res.status(403).send('forbidden')
  }

  // Clear the metrics data generated by the last request
  DATABASE_CPU.reset()
  DATABASE_MEMORY.reset()

  const databaseMetrics = await ClusterService.getPodMetrics(
    ClusterService.DB_NAMESPACE,
    ClusterService.LABEL_DATABASE,
    'DATABASE',
  )

  for (const metric of databaseMetrics) {
    updateMetrics(metric)
  }

  res.set('Content-Type', 'text/plain')
  res.send(await register.metrics())
}

export default getDatabaseMetrics
